<template>
  <div class="app-container">

    <div class="header">
      <el-button type="primary" @click="dialogSaveStudentForm = true" size="mini">添加</el-button>
      <el-input style="width: 300px; margin-left: 100px;" size="mini" placeholder="输入关键字搜索" v-model="studentListForm.mimo" @change="studentSearch" @input="checkVal">
        <i slot="suffix" class="el-icon-search" ></i>
      </el-input>
    </div>

    <!-- 添加弹出框 -->
    <el-dialog title="添加" :visible.sync="dialogSaveStudentForm" :close-on-click-modal="false" @close="closeSaveStudentForm">
      <el-form ref="form" :model="form" label-width="100px" :rules="saveRules">
        <el-form-item label="账号" prop="name">
          <el-input v-model="form.name" />
        </el-form-item>
        <el-form-item label="学号" prop="number">
          <el-input v-model="form.number"/>
        </el-form-item>
        <el-form-item label="年级" prop="grade">
          <el-input v-model="form.grade" />
        </el-form-item>
        <el-form-item label="班级" prop="studentClass">
          <el-input v-model="form.studentClass" />
        </el-form-item>
        <el-form-item label="联系电话" prop="phone">
          <el-input v-model="form.phone"/>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="saveStudentData" :loading="loading">提交</el-button>
          <el-button @click="closeSaveStudentForm">取消</el-button>
        </el-form-item>
      </el-form>
    </el-dialog>

    <!-- 修改学生弹出框 -->
    <el-dialog title="修改学生" :visible.sync="dialpgEditStudentForm" :close-on-click-modal="false" @close="closeEdit">
      <el-form ref="editForm" :model="editForm" label-width="100px" :rules="editRules">
        <el-form-item label="学生名字" prop="studentName">
          <el-input v-model="editForm.studentName" />
        </el-form-item>
        <el-form-item label="学号" prop="studentNumber">
          <el-input v-model="editForm.studentNumber" />
        </el-form-item>
        <el-form-item label="年级" prop="grade">
          <el-input v-model="editForm.grade" />
        </el-form-item>
        <el-form-item label="班级" prop="studentClass">
          <el-input v-model="editForm.studentClass"/>
        </el-form-item>
        <el-form-item label="手机号" prop="studentPhone">
          <el-input v-model="editForm.studentPhone"/>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" :loading="loading" @click="edit">提交</el-button>
          <el-button @click="cancelEdit">取消</el-button>
        </el-form-item>
      </el-form>
    </el-dialog>

    <!-- 学生列表 -->
    <div class="content">
      <el-table :data="studentList" style="width: 100%;" stripe>
        <el-table-column label="学生信息">
          <el-table-column label="账号" prop="studentName">
            <template slot-scope="scope">
              <div>{{ scope.row.studentName }}</div>
            </template>
          </el-table-column>
          <el-table-column label="年级" prop="grade">
            <template slot-scope="scope">
              <div>{{ scope.row.grade }}</div>
            </template>
          </el-table-column>
          <el-table-column label="班级" prop="studentClass">
            <template slot-scope="scope">
              <div>{{ scope.row.studentClass }}班</div>
            </template>
          </el-table-column>

          <el-table-column label="手机号" prop="studentPhone">
            <template slot-scope="scope">
              <div>{{ scope.row.studentPhone }}</div>
            </template>
          </el-table-column>
          <el-table-column label="学号" prop="studentNumber">
            <template slot-scope="scope">
              <div>{{ scope.row.studentNumber }}</div>
            </template>
          </el-table-column>
        </el-table-column>
        <el-table-column label="操作">
          <el-table-column label="修改">
            <template slot-scope="scope">
              <el-button type="primary" circle icon="el-icon-edit" @click="showEdit(scope.row.studentId)"></el-button>
            </template>
          </el-table-column>
          <el-table-column label="删除">
            <template slot-scope="scope">
              <el-button type="danger" circle icon="el-icon-delete" @click="delStudent(scope.row.studentId)"></el-button>
            </template>
          </el-table-column>
        </el-table-column>
      </el-table>
      <el-pagination @size-change="adminListSizeChange" @current-change="adminListCurrentChange"
        :page-size="studentListForm.size" :page-sizes="[10, 20, 30]" layout="total, sizes, prev, pager, next"
        :total="studentListTotal" style="margin-top: 20px;">
      </el-pagination>
    </div>


  </div>
</template>

<script>
import utils from '@/utils/checkLogin'
import { Message } from 'element-ui'
import { saveStudent, getStudentList, deleteStudent, getUpdateStudentInfo, editStudent } from '@/api/api'

export default {
  data() {
    return {
      loading: false,
      form: {
        name: '',
        number: null, 
        studentClass: '',
        phone: null,
        grade: ''
      },
      dialogSaveStudentForm: false,
      saveRules: {
        name: [
          { required: true, message: '请输入账号', trigger: 'change' },
          { max: 5, message: '账号长度不能大于 5 个字符', trigger: 'change' }
        ],
        number: [
          { required: true, message: '请输入学号', trigger: 'change' },
          { type: 'number', message: '输入的值必须为数字', trigger: 'blur', transform: (value) => Number(value) }
        ],
        studentClass: [
          { required: true, message: '请输入班级', trigger: 'change' }
        ],
        grade: [
          { required: true, message: '请输入年级', trigger: 'change' }
        ],
        phone: [
          { required: true, message: '请输入联系电话', trigger: 'change' },
          { pattern: /^[1][3,4,5,7,8][0-9]{9}$/, message: '请输入正确的手机号', trigger: 'change' }
        ],
      },
      studentList: [],
      studentListForm: {
        page: 1,
        size: 10,
        mimo: ''
      },
      studentListTotal: null,
      editForm: {
        studentId: null,
        studentName: '',
        studentNumber: '',
        studentClass: '',
        grade: '',
        studentPhone: null
      },
      dialpgEditStudentForm: false,
      editRules: {
        studentNumber: [
          { required: true, message: '请输入学号', trigger: 'change' },
          { type: 'number', message: '输入的值必须为数字', trigger: 'blur', transform: (value) => Number(value) }
        ],
        studentName: [
        { required: true, message: '请输入学号', trigger: 'change' },
        { max: 5, message: '账号长度不能大于 5 个字符', trigger: 'change' }
        ],
        grade: [
          { required: true, message: '请输入年级', trigger: 'change' }
        ],
        studentClass: [
          { required: true, message: '请输入班级', trigger: 'change' }
        ],
        studentPhone: [
          { required: true, message: '请输入联系电话', trigger: 'change' },
          { pattern: /^[1][3,4,5,7,8][0-9]{9}$/, message: '请输入正确的手机号', trigger: 'change' }
        ],
      },
    }
  },
  methods: {
    saveStudentData() {
      console.log(this.form)
      this.$refs.form.validate(valid => {
        // 表单验证失败
        if (!valid) {
          Message({
            message: '请检查表单！',
            type: 'warning',
            duration: 2000
          })
          return false
        } else {
          // 表单验证成功
          saveStudent(this.form).then((res) => {
            if (res.code == 200) {
              Message({
                message: '添加成功',
                type: 'success',
                duration: 3000
              })
              console.log('添加学生', res)
              this.loading = true
              setTimeout(() => {
                this.dialogSaveStudentForm = false
                this.loading = false
                this.getStudentListData()
                this.$nextTick(() => {
                  // 添加成功时，置空 form 表单
                  this.$refs.form.resetFields()
                })
              }, 2000)
            }
          })
        }
      })

    },
    closeSaveStudentForm() {
      this.dialogSaveStudentForm = false
      this.$nextTick(() => {
        // 关掉 dialog 时，置空 form 表单
        this.$refs.form.resetFields()
      })

    },
    getStudentListData() {
      getStudentList(this.studentListForm).then((res) => {
        if (res.code == 200) {
          console.log('学生列表', res);
          this.studentList = res.data.data
          this.studentListTotal = res.data.total
        }
      })
    },
    // 学生列表，切换每页条数时
    adminListSizeChange(e) {
      this.studentListForm.size = e
      this.getStudentListData()
    },

    // 学生列表，点击切换页码时
    adminListCurrentChange(e) {
      this.studentListForm.page = e
      this.getStudentListData()
    },

    // 展示修改弹出框
    showEdit(studentId) {
      this.dialpgEditStudentForm = true
      this.editForm.studentId = studentId
      // 数据回显
      getUpdateStudentInfo(studentId).then((res) => {
        if (res.code == 200) {
          console.log('修改学生（数据回显）', res)
          this.editForm.studentId = res.data.studentId
          this.editForm.studentClass = res.data.studentClass
          this.editForm.grade = res.data.grade
          this.editForm.studentName = res.data.studentName
          this.editForm.studentNumber = res.data.studentNumber
          this.editForm.studentPhone = res.data.studentPhone
        }
      })
    },

    // 关闭修改弹出框
    closeEdit() {
      this.dialpgEditStudentForm = false
    },

    // 编辑-提交
    edit() {
      this.$refs.editForm.validate(valid => {
        if (!valid) {
          Message({
            message: '请检查表单！',
            type: 'warning',
            duration: 2000
          })
          return false;
        } else {
          editStudent(this.editForm).then((res) => {
            if (res.code == 200) {
              console.log('修改学生', res);
              Message({
                message: '修改成功',
                type: 'success',
                duration: 3000
              })
              this.loading = true
              setTimeout(() => {
                this.dialpgEditStudentForm = false
                this.loading = false
              }, 2000)
              this.getStudentListData()
            }
          })
        }
      })
    },

    // 取消编辑
    cancelEdit() {
      this.dialpgEditStudentForm = false
    },

    delStudent(id) {
      this.$confirm('是否删除该学生?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        deleteStudent(id).then((res) => {
          if (res.code == 200) {
            console.log('删除成功', res);
            this.$message({
              type: 'success',
              message: '删除成功',
              duration: 3000
            })
            this.getStudentListData()
          } else {
            this.$message({
              type: 'error',
              message: '删除失败',
              duration: 3000
            })
          }
        })
      }).catch(() => {
      })

    },
    // 搜索
    studentSearch() {
      console.log(JSON.stringify(this.studentListForm))
      this.getStudentListData()
    },
    // 如果搜索框的值为空，刷新一下列表
    checkVal() {
      if (this.studentListForm.mimo == '') {
        this.getStudentListData()  
      }
    }
  },
  created() {
    utils.checkLogin()
    this.getStudentListData()
  }
}
</script>

<style lang="less" scoped>
.app-container {
  padding: 40px;

  .header {
    align-items: center;
    display: flex;
    margin-bottom: 20px;

    .el-icon-search {
      cursor: pointer;
      margin-right: 4px;
      margin-top: 8px;
    }
  }

  .content {
    text-align: center;
  }
}
</style>

